// pages/goodDetail/goodDetail.jsco
const app=getApp()
const config = require('../config');
const { API_BASE_URL } = config;
Page({
  data: {
    product: null
  },
  onLoad: function(options) { 
    const that = this; // 保存this的引用，因为wx.request的回调函数中this指向会变化    
    const token = wx.getStorageSync('token');
    const id = options.id;
    console.log("存储 token:", token);
    console.log("商品id",id);

    if (!token) {
      console.warn('没有找到 token');
      return;
    }

    wx.request({
      url: `${API_BASE_URL}/product/get/vo`,
      method: 'GET',
      data: {
        id: id
      },
      header: {
        'satoken': token // 添加 token 到请求头
      },
      success(res) {
        const resData = res.data.data;
        console.log("product:", resData)
        that.setData({
          product: resData
        });
      },
      fail(err) {
        console.error('网络请求失败', err);
      }
    });
  },
  //分享给好友
  onShareAppMessage(){
    return{
      title:this.data.good.title,
      //别人点击分享进入的页面
      path:'/pages/goodDetail/goodDetail?id='+this.data.good._id,
      imageUrl:this.data.good.cover
    }
  },
  //分享到朋友圈
  onShareTimeline(){
    return{
      title:this.data.good.title,
    query:{
      id:this.data.good._id
    },
    imageUrl:this.data.good.cover
    }
  },
  //添加当前商品到购物车
  addCart(){
    //判断是否登录
    if(!wx.getStorageSync('userInfo')){
      wx.showModal({
        title: '请先登录',
        content: '为了您的安全请先登录',
        success: (res) => {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/my/my',
            })
          }
        }
      })
    }

    var index=-1;
    this.setData({
      cartList:app.globalData.cartList
    })
    for (let i = 0; i < this.data.cartList.length; i++) {  
      console.log(this.data.cartList[i]);  
      if(this.data.cartList[i]._id==this.data.good._id){
        index=i;
      }
  }
  if(index!=-1){
    this.data.cartList[index].number=this.data.cartList[index].number+1
    app.globalData.cartList=this.data.cartList;
    wx.setStorageSync('cartList', app.globalData.cartList)
  }else{
    this.data.good.number=1
    this.data.good.choose=true
    app.globalData.cartList.push(this.data.good)
    app.globalData.cartList=this.data.cartList;
    wx.setStorageSync('cartList', app.globalData.cartList)
  }
    wx.showToast({
      title: '添加成功！',
    })
    this.setData({
      cartList:app.globalData.cartList
    })
    wx.setStorageSync('cartList', app.globalData.cartList)
  },
  toOrders(){
    let orderList = []
    orderList.push(this.data.good)
    app.globalData.orderList = orderList
    // wx.setStorageSync('orderList', app.globalData.orderList)
    wx.navigateTo({
      url: '/pages/order/order',
    })
  },
  tobuyCar(){
    wx.switchTab({
      url: '/pages/buy/buy',
    })
  }
})